<template>
    <div>

        <el-row v-if="showTabOption&&!sksUtils.isNullOrUndefined(mainTable.tabsFilterOptionList)" style="margin-bottom: 10px;">
            <el-col :span="24">
                <el-tabs class="deleteBorder" @tab-click="handleChangeTabsFilterValueChange()" v-model="mainTable.tabsFilterValue">
                    <el-tab-pane v-for="(item, index) in mainTable.tabsFilterOptionList"
                                 :key="`${item.dictValue}`"
                                 :disabled="mainTable.loading"
                                 :label="item.dictLabel"
                                 :name="''+item.dictValue">
                    </el-tab-pane>
                </el-tabs>
                <!--                <el-radio-group-->
                <!--                    :size="systemConfig.buttonSize"-->
                <!--                    @change="handleChangeTabsFilterValueChange()" v-model="mainTable.tabsFilterValue">-->
                <!--                    <el-radio-button v-for="(item, index) in mainTable.tabsFilterOptionList"-->
                <!--                                 :disabled="mainTable.loading"-->
                <!--                                 :label="item.dictValue">-->
                <!--                        {{item.dictLabel}}-->
                <!--                    </el-radio-button>-->
                <!--                </el-radio-group>-->
            </el-col>
        </el-row>
        <slot name="tabsFilterOptionBottom"></slot>

        <!--        :gutter="10"-->
        <el-row v-if="visibleTop" :gutter="10" class="mb8 ml10">
            <slot name="top"></slot>
            <sks-right-toolbar
                :mainTable="mainTable"
                :showRefreshButton="showRefreshButton"
                :showTablePropName.sync="mainTable.showTablePropName"
                :showTable.sync="mainTable.showTable" :showAllColumnButton="mainTable.showAllColumnButton" :showAllColumn.sync="mainTable.showAllColumn"
                :showSearchButton.sync="mainTable.showSearchButton"
                :showSearch.sync="mainTable.showSearch" @queryTable="refreshTable()">
                <template slot="prefix">
                    <slot name="topPrefix"></slot>
                </template>
            </sks-right-toolbar>
        </el-row>
        <slot name="topRowAfter"></slot>
        <!--        show-summary-->
<!--       header-dragend 列宽拖动-->
        <el-table
            @header-dragend="()=>$emit('headerDragend',...arguments)"
            :reRender="initTableDragSort()"
            :rowKey="mainTable.rowKey"
            :ref="mainTable.uuid"
            v-if="mainTable.showTable" v-loading="mainTable.loading" :data="mainTable.list"   @selection-change="handleSelectionChange"
            :highlight-current-row="highlightCurrentRow"
            :row-style="rowStyle"
            @row-click="rowClickMainTable"
            :style="tableStyle"
            :element-loading-text="mainTable.elementLoadingText"
            :default-expand-all="mainTable.defaultExpandAll"
            :header-cell-style="headerCellStyle"
        >
<!--            <el-table-column width="100"></el-table-column>-->
            <el-table-column v-if="mainTable.dragSort" label="拖动排序" type="index" class-name="allowDrag"  align="center" min-width="5%"/>
            <slot name="tableColumnList-before"></slot>

            <template v-if="mainTable.tableColumnListEnable&&sksUtils.notNullAndNotUndefined(sksUtils.safeGet(mainTable,'tableColumnList'))">
                <!--        <el-table-column>-->
                <!--        {{safeGet(mainTable,'tableColumnList')}}-->
                <!--        </el-table-column>-->
                <!--        动态列,列显示错位,官方建议增加一个 width为1的列-->
<!--                <el-table-column width="1"></el-table-column>-->
<!--                这里如果使用 span 则顺序会错 :key="item.vueVirtualUUID"-->
                <template  v-for="(item,itemIndex) in mainTable.tableColumnList">
                    <template v-if="sksUtils.strIsEmpty(item.slot)" >
                        <!--                    当表格列项动态显示时，多次刷新，造成渲染时出现列项错乱现象
                                            加上 key="itemIndex"
                        -->
                        <el-table-column
                            :show-overflow-tooltip="sksUtils.ifNull(item.showOverflowTooltip,webListPropPropConfig.showOverflowTooltip)"
                            :className="item.className"
                            :filters="item.filters"
                            :align="item.align||webListPropPropConfig.align" :prop="item.prop"
                            :width="item.width"
                            :min-width="item.minWidth"
                            :label="item.label"
                            v-if="isShowColumn(item)&&(item.visible||mainTable.showAllColumn)"
                            :render-header="(h,args)=>renderHeader(h,args,item)">
                            <template slot-scope="scope">
                                <template v-if="item.htmlType=='none'">
                                    <slot :name="`none-${item.prop}`" :row="scope.row" :column="scope.column" :$index="scope.$index" :item="item">
                                    </slot>
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeYmd'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{y}-{m}-{d}')}}
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeMdHm'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{m}-{d} {h}:{i}')}}
                                </template>
                                <template v-else-if="item.htmlType=='parseTimeYmdHm'">
                                    {{sksUtils.parseTime(sksUtils.safeGet(scope.row,item.prop),'{y}-{m}-{d} {h}:{i}')}}
                                </template>
                                <template v-else-if="item.htmlType=='dictFormatObject'">
                                    <!--                                    <div :class="safeGet(scope.row,`${item.prop}.cssClass`)">{{sksUtils.safeGet(scope.row,`${item.prop}.dictLabel`)}}</div>-->
                                    <SksDictLabelTag :dict-data="sksUtils.safeGet(scope.row,`${item.prop}`)"></SksDictLabelTag>
                                </template>
                                <template v-else-if="item.htmlType=='no0InfoYes1Danger'">
                                    <el-tag type="danger" v-if="sksUtils.safeGet(scope.row,item.prop)==1">
                                        是
                                    </el-tag>
                                    <el-tag type="info" v-else>
                                        否
                                    </el-tag>
                                </template>
                                <template v-else-if="item.htmlType=='unFinish0WarningFinish1Success'">
                                    <el-tag type="success" v-if="sksUtils.safeGet(scope.row,item.prop)==1">
                                        已完结
                                    </el-tag>
                                    <el-tag type="warning" v-else>
                                        未完结
                                    </el-tag>
                                </template>
                                <template v-else-if="item.htmlType=='negateNumber'">
                                    {{sksUtils.negateNumber(sksUtils.safeGet(scope.row,item.prop))}}
                                </template>
                                <template v-else-if="item.htmlType=='absNumber'">
                                    {{sksUtils.absNumber(sksUtils.safeGet(scope.row,item.prop))}}
                                </template>
                                <template v-else-if="item.htmlType=='elImageByImgUrl'">
                                    <template v-if="!sksUtils.strIsEmpty(sksUtils.safeGet(scope.row,item.prop))">
                                        <sksImageUseImgUrl v-model="scope.row[item.prop]"/>
                                    </template>
                                </template>
                                <template v-else>
                                    <template v-if="item.textColor=='none'" >
                                        {{sksUtils.safeGet(scope.row,item.prop)}}
                                    </template>
                                    <template v-else>
                                        <div :style="{color: item.textColor}">{{sksUtils.safeGet(scope.row,item.prop)}}</div>
                                    </template>
                                </template>
                            </template>
                        </el-table-column>
                    </template>
                    <template v-else>
                        <slot  :name="'custom-'+item.slot" :item="item" :webListPropPropConfig="webListPropPropConfig" :renderHeader="renderHeader">
                        </slot>
                    </template>
                </template>
            </template>
            <template v-else>
                <slot name="default"></slot>
            </template>
            <slot name="tableColumnList-after"></slot>
        </el-table>
        <SksPagination
            :page-sizes="paginationPageSizes"
            v-if="mainTable.showPagination"
            v-show="mainTable.total>0"
            :total="mainTable.total"
            :page.sync="mainTable.queryParams.pageNum"
            :limit.sync="mainTable.queryParams.pageSize"
            @pagination="refreshTable()"
        />

        <el-dialog :close-on-click-modal="true" :title="propTableDialogInfo.title" :visible.sync="propTableDialogInfo.showDialog" width="800px"  :append-to-body="true">
            <SksTablePropTable :item="propTableDialogInfo.data"
                               @showDictDataDialog="(args)=>$emit('showDictDataDialog',args)"
                               @jumpToDictData="(args)=>$emit('jumpToDictData',args)">
            </SksTablePropTable>
        </el-dialog>
    </div>
</template>

<script>
import Sortable from "sortablejs";
import clipboard from "../../../clipboard";
import {
    defaultSksTableColumnData,
    resetMainTableQueryParamsByTabsFilterValue,
    rowStyleElTable
} from "../../../sks-app-utils";
import {mergeFromObject} from "../../../core";
import {newSksDialogInfo} from "../../../sks-model-utils";


export default {
    name: 'SksTable',
    components: {  },
    props:{
        //显示刷新按钮
        showRefreshButton: {
            type: Boolean,
            default: true,
        },
        //显示标签页切换
        showTabOption:{
            type: Boolean,
            default: true,
        },
        //显示顶部工具条
        visibleTop: {
            type: Boolean,
            default: true,
        },
        tableStyle: [Object,String],
        mainTable:[Object],
        highlightCurrentRow: {
            type: Boolean,
            default: true
        },
        rowStyle:{
            type:  [Object, Function],
            default: ()=>{
                return rowStyleElTable
            }
        },
        tabsFilterValueChange:[Function],
        paginationPageSizes: [Array],
        headerCellStyle: [Function],

        //是否显示列,return true: 显示,false不显示
        //columnIfFunc(item)
        columnIfFunc:[Function],

    },
    data(){
        return {
            webListPropPropConfig: defaultSksTableColumnData,

            propTableDialogInfo: mergeFromObject({},newSksDialogInfo(),{
                data:{},
                showDialog: false,
                title: '列表字段属性',
            }),
        }
    },
    beforeDestroy() {
        if (this.mainTable.dragSortTableTmp) {
            this.mainTable.dragSortTableTmp.destroy()
        }
    },
    mounted() {
        this.initTableDragSort()
    },
    methods:{
        isShowColumn(item){
            if(this.sksUtils.isNullOrUndefined(this.columnIfFunc)){
                return true;
            }
            return this.columnIfFunc(item)
        },
        //初始化拖动排序列
        initTableDragSort(){
            if(this.mainTable.dragSort){
                this.$nextTick(()=>{
                    const el = this.$refs[this.mainTable.uuid].$el.querySelectorAll(".el-table__body-wrapper > table > tbody")[0];
                    console.log("uuid",this.mainTable.uuid)
                    console.log("el",el)
                    this.mainTable.dragSortTableTmp= Sortable.create(el, {
                        handle: ".allowDrag",
                        onEnd: (evt) => {
                            let list = this.mainTable.list;
                            const targetRow = list.splice(evt.oldIndex, 1)[0];
                            list.splice(evt.newIndex, 0, targetRow);
                            const ids=list.map(item=>item[this.mainTable.uniqueId])
                            console.log("list.ids",ids)
                            // for (let index in this.list) {
                            //     list[index][this.mainTable.dragSortPropName] = parseInt(index) + 1;
                            // }
                            // this.$set(this.mainTable,'list',list);
                            this.$emit('dragSort')
                        }
                    });
                })
            }
        },
        handleChangeTabsFilterValueChange(){
            // console.log("mainTable.tabsFilterValue",this.mainTable.tabsFilterValue)
            let tabsFilterValue = this.mainTable.tabsFilterValue
            // console.log("tabsFilterValueChange",this.tabsFilterValueChange)
            if(this.tabsFilterValueChange){
                this.tabsFilterValueChange(tabsFilterValue)
                return
            }
            // let row = findRowInListFromAttrName(this.mainTable.tabsFilterOptionList,'dictValue',tabsFilterValue)
            // this.$emit('tabsFilterValueChange',{tabsFilterValue: tabsFilterValue,row:row})
            // this.mergeFromObject(this.mainTable.queryParams.sksParams,this.mainTable.tabsSksParamsDefaultSetting,row?.sksParams)
            // this.mainTable.queryParams.mybatisRestrictionName=row?.mybatisRestrictionName
            resetMainTableQueryParamsByTabsFilterValue(this.mainTable)
            this.refreshTable()

        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.mainTable.selection=selection
            this.mainTable.ids = selection.map(item => item[this.mainTable.uniqueId]);
            this.mainTable.single = selection.length != 1;
            this.mainTable.multiple = !selection.length;
            this.$emit('selectionChangeAfter',selection)
        },

        rowClickMainTable(row){
            this.mainTable.currentRow=row
            this.$emit('rowClickAfter',row)
        },
        refreshTable(){
            this.$emit('refresh')
        },
        renderHeader(h, args,item){
            let { column, $index }=args
            // console.log('renderHeader.h',h)
            // console.log('renderHeader.args',args)
            if(!this.mainTable.showTablePropName){
                return h('el-row',{}, [
                    h('el-col', {}, column.label ),
                ]);
            }
            return (
                <el-row>
                    <el-col>
                        {column.label}
                    </el-col>
                    <el-col>
                        <p style="display: inline;">
                            <el-tag onClick={(e)=>clipboard(item.prop,e)}>
                                {item.prop}
                            </el-tag>
                            <el-tooltip className="item" effect="dark" content="显示更多配置" placement="top">
                                <el-button size="mini" circle icon="el-icon-search"
                                           onClick={()=>this.showPropTable(item)}
                                ></el-button>
                            </el-tooltip>
                        </p>
                    </el-col>
                </el-row>
            )
            // {
            //
            //     Object.keys(item).map(itemProp => {
            //         return
            //         <el-row>
            //             <el-col span={12} style="white-space:nowrap">
            //             {itemProp}
            //             </el-col>
            //             <el-col span={12} style="white-space:nowrap">
            //                 <template v-if={itemProp=='handleDictType'}>
            //                     <router-link to={'/dict/type/data/' + item[itemProp]} class="link-type">
            //                         <span>{item[itemProp]}</span>
            //                     </router-link>
            //                 </template>
            //                 <template v-else>
            //                     {item[itemProp]}
            //                 </template>
            //             </el-col>
            //     </el-row>
            //     })
            // }
            // return h('el-row',{}, [
            //     h('el-col', {}, column.label ),
            //     h('el-col', {},[
            //         h('div',{},item.prop)
            //     ]),
            // ]);

            // return h('span', {}, [
            //     h('span', {}, column.label),
            //     h('el-popover', { props: { placement: 'top-start', width: '200', trigger: 'hover', content: '城市价格为该城市所有加盟商价格的最高价' }}, [
            //         h('i', { slot: 'reference', class:'el-icon-question'}, '')
            //     ])
            // ])
            //         <el-col>
            //         <el-popover
            //     placement="right"
            //     width="400"
            //     trigger="click">
            //         <el-table data={item}>
            //         <el-table-column width="150" property="date" label="日期"></el-table-column>
            //     <el-table-column width="100" property="name" label="姓名"></el-table-column>
            //     <el-table-column width="300" property="address" label="地址"></el-table-column>
            // </el-table>
            // <el-button slot="reference">click 激活</el-button>
            // </el-popover>
            // </el-col>
        },
        showPropTable(item){
            this.propTableDialogInfo.data=item
            console.log("item",item)
            this.propTableDialogInfo.showDialog = true
        },
    }
}
</script>



<style>
/*去掉el-tab-pane底部灰色线条*/
.deleteBorder .el-tabs__nav-wrap::after {
    height: 0;
}

.deleteBorder .el-tabs__content {
    overflow-x: hidden;
}
/*//高亮点击的行*/
.el-table__body tr.current-row>td {
//background: rgb(77, 195, 255, 0.5) !important;
    background-color: #DCDCDC !important;
    color: #000000;
}
/*//鼠标滑过时高亮行*/
.el-table__body tr:hover>td{
//background: rgb(77, 195, 255, 0.2);
    background-color: #d7dcdc !important;
//background: none;
}

.el-table__header-wrapper>table {
    border-collapse: collapse;
    /* margin: 1rem 0; */
    margin: 0px;
    display: block;
    overflow-x: auto;
}

.el-table__body-wrapper>table {
    border-collapse: collapse;
    /* margin: 1rem 0; */
    margin: 0px;
    display: block;
    overflow-x: auto;
}
</style>
